#include "stdafx.h"

#include "path_manager.h"

PathManager::PathManager()
{
	m_globalPath = "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
	m_userPath = "Environment";
	update();
}

PathManager::~PathManager()
{
}

void
PathManager::clear()
{
	m_entriesListGlobal.clear();
	m_entriesListUser.clear();
}

void
PathManager::update()
{
	updatePath();
	clear();
	updateLists();
}

void
PathManager::updatePath()
{
	// Registry Magic
	HKEY key;
	char	path[4096];
	DWORD	size;

	if (!RegOpenKeyEx(
				HKEY_LOCAL_MACHINE
			,	m_globalPath
			,	0
			,	KEY_WRITE
			,	&key
			)
		)
		RegSetValueEx(
				key
			,	"Path"
			,	0
			,	REG_EXPAND_SZ
			,	(unsigned char *)path
			,	strlen(path) + 1
			);
	
	if ( !RegOpenKeyEx(
				HKEY_CURRENT_USER
			,	m_userPath
			,	0
			,	KEY_WRITE
			,	&key
			)
		)
		RegSetValueEx(
				key
			,	"Path"
			,	0
			,	REG_EXPAND_SZ
			,	(unsigned char *)path
			,	strlen(path) + 1
			);
}



void
PathManager::updateLists()
{
	HKEY	key;
	char	path[4096];
	DWORD	size;

	if ( !RegOpenKeyEx(
				HKEY_LOCAL_MACHINE
			,	"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"
			,	0
			,	KEY_READ
			,	&key
			)
		)
	{
		if (!RegQueryValueEx(key, "Path", NULL, NULL, (unsigned char *)path, &size))
			fillStringVector( path, m_entriesListGlobal );
	}
#ifdef _DEBUG
	else MessageBox( NULL, "error while opening global path", "error", MB_OK );
#endif

	if ( !RegOpenKeyEx(
				HKEY_CURRENT_USER
			,	m_userPath
			,	0
			,	KEY_READ
			,	&key
			)
		)
	{
		if (!RegQueryValueEx(key, "Path", NULL, NULL, (unsigned char *)path, &size))
			fillStringVector( path, m_entriesListUser );
	}
#ifdef _DEBUG
	else MessageBox( NULL, "error while opening global path", "error", MB_OK );

	diagnosticMessage( m_entriesListGlobal, "Global Path" );
	diagnosticMessage( m_entriesListUser, "User Path" );
#endif
}


void
PathManager::fillStringVector( std::string _str, std::list< std::string >& _list )
{
	while ( !_str.empty() )
	{
		int pos = _str.find_first_of(';');
		std::string newEntry;
		if ( pos != -1 ) // we found ; in string
		{
			newEntry = _str.substr( 0, pos );
			_str = _str.substr( pos + 1 );
		}
		else // the last value in string without ;
		{
			newEntry = _str;
			_str.clear();
		}
		_list.push_back( newEntry );
	}
}

void
PathManager::diagnosticMessage(
	std::list< std::string >& _list
,	const char* _title
)
{
	std::string diagString;
	std::list<std::string>::const_iterator it = _list.begin();
	while ( it != _list.end() )
		diagString += *it++ + '\n';
	
	MessageBox( NULL, diagString.c_str(), _title, MB_OK );
}